﻿using System;
using ctlUSBHID;

namespace BeerManagementSystem
{
    public class MagTekCardReader : ICardReader
    {
        private bool _ready;
        private bool _accepting;
        private USBHID _reader;
/*
        LogWriter _log;
*/
        
       

        public MagTekCardReader()
        {
            _reader = new USBHID();
            _reader.CardDataChanged += _reader_CardDataChanged;
            _reader.PortOpen = true;
            _ready = true;
        }

        void _reader_CardDataChanged()
        {
            String data = _reader.GetTrack(1);

            if (data.Length == 7)
            {
                try
                {
                    Read(Convert.ToInt32(data.Substring(1, 5)));
                    //log.WriteMessage("CardReader: read : " + data);
                }
                catch (Exception)
                {
                }
            }
            else
            {
                CardInvalid(this, EventArgs.Empty);
            }
        }

        public void AcceptNextCard()
        {
            _accepting = true;
        }

        public void Read(int cardIdentity)
        {
            if (_accepting)
            {
                _accepting = false;

                switch (cardIdentity)
                {
                    case 79:
                        BarrelReset(this, null);
                        break;
                    case 78:
                        ResetLastTransaction(this, null);
                        break;
                    case 80:
                        Einladen(this, null);
                        break;
                    default:
                        CardRead(this, new CardReadEventArgs(cardIdentity));
                        break;
                }

            }
        }

        public bool IsReady()
        {
            return _ready;
        }
        public void close()
        {
            this.close();
            //log.WriteMessage("Cardreader: shutdown");
            
        }
        public event EventHandler<CardReadEventArgs> CardRead;

        public event EventHandler CardInvalid;

        public event EventHandler BarrelReset;

        public event EventHandler ResetLastTransaction;

        public event EventHandler Einladen;

        

    }
}
